<template>
    <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="formInline" :rules="rules" ref="formInline" class="formInline" label-width="80px" slot="form">
                <!-- edit by cuihd at 2018/8/8 -->
                <!-- 将原“查询条件”的所属省、市区、区县删掉，这些查询条件区分度小，可能会查出几十万的数据 -->
                <!-- 直接使用区分度高的学校名称来查询，学校名称为必填项 -->
                <!-- <el-row :gutter="41">
                     <el-col :span="8">
                        <el-form-item label="所属省" prop="fProvinceId">
                            <province v-model="formInline.fProvinceId"></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市区">
                            <city v-model="formInline.fCityId" :province="formInline.fProvinceId"></city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区县">
                            <region v-model="formInline.fAreaId" :city="formInline.fCityId"></region>
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="学校名称" prop="schoolName">
                            <school v-model="formInline.schoolName" :provinceId="formInline.fProvinceId" :cityId="formInline.fCityId" :areaId="formInline.fAreaId" style="width:100%" @change='schoolChange'></school>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="姓名">
                            <el-input v-model="formInline.name" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                    </el-col>
                     <el-col :span="8">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="formInline.phone" placeholder="请输入手机号" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="e学云ID号" prop="exueCode">
                            <el-input v-model="formInline.exueCode" placeholder="请输入e学云ID号" :maxlength="10"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="top-line">
                    <el-button type="primary"  @click="search('formInline')">查询</el-button>
                </div>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button @click="showAddTea">添加教师</el-button>
                    <el-button @click="showLotImport">批量导入</el-button>
                    <el-button @click="deleteRoleLots">批量删除</el-button>
                    <!--  后端教师异步删除，前端无奈添加，后期继续优化 -->
                    <!-- <span style="color:#f00">（批量删除教师时，需要等候一段时间手动刷新哟）</span>  -->
                </div>
            </div>
            <el-table border :data="AnnounceList" style="width: 100%"
             @selection-change="handleSelectionChange"
            ref="multipleTable" v-loading="loading">
                <el-table-column align="center" type="selection" width="55"></el-table-column>
                <el-table-column align="center" label="e学云ID号" min-width="120">
                      <template scope="scope">
                        <span>{{scope.row.exueCode?scope.row.exueCode:'--'}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="姓名" align="center" min-width="80">
                      <template scope="scope">
                        <span>{{scope.row.name?scope.row.name:'--'}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="注册手机号" align="center" min-width="130">
                     <template scope="scope">
                        <span>{{scope.row.phone?scope.row.phone:'--'}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" min-width="200">
                    <template scope="scope">
                        <span>{{scope.row.createTime?scope.row.createTime:'--'}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="最后登录时间" align="center"  min-width="200">
                     <template scope="scope">
                        <span>{{scope.row.lastLoginTime?scope.row.lastLoginTime:'--'}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="其他操作" width="320">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="initPassword(scope.row.teacherId,scope.row.name)">初始化密码</el-button>
                        <el-button type="text" class="btn-success" @click="goToCorrect(scope.row.teacherId)">修改</el-button>
                        <el-button type="text" class="btn-success" @click="deleteListOne(scope.row.teacherId)">删除</el-button>
                        <el-button type="text" class="btn-success" @click="teacherClass(scope.row.teacherId)">任教班级</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" 
                :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <addTeaDialog :addTeaData="addTeaData" @search-list="addSearch"> </addTeaDialog>
        <importLotDialog :addImportData="addImportData" @importProgress="importProgress"> </importLotDialog>
        <!-- created by cuihd at 20180709 优化批量删除教师 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>

<script>
import {getTeachersByPage, initPassword, batchDeleteTeacher, batchDeleteTeacherProgress, batchImportForTeacherProgress} from 'api/teacherManage';
import TableLayout from 'components/TableLayout';
import addTeaDialog from './addTea';
import importLotDialog from './importLot';
import { mapState, mapActions, mapGetters } from 'vuex';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import school from 'components/SchoolClasss/school';
import validate from '@/utils/validate';
export default {
    name: 'teacherManageList',
    components: { TableLayout, addTeaDialog, importLotDialog, province, city, region, school},
    data() {
        return {
            loading: false,
            formInline: { // 查询 表单数据
                fProvinceId: '', // 省份
                fCityId: '', // 市区
                fAreaId: '', // 区县
                schoolName: '', // 学校名字
                areaId: '', // 
                name: '',
                phone: '',
                exueCode: '',
                schoolNameList: [], // 学校名称列表
                schoolId: ''
            },
            // 教职工类型 教职工1,非教职工0
            workTypeArr: [{
                workTypeName: '教职工',
                workTypeId: '1'
            }, {
                workTypeName: '非教职工',
                workTypeId: '0'
            }],
            checked: true,
            AnnounceList: [],
            dataNum: 1, // 表格1显示条数，初始为1
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            addTeaData: {
                dialogAddTea: false,
                provinceId: ''
            },
            addImportData: {
                dialogLotImport: false,
                provinceId: ''
            },
            dialog: {
                dialogFormVisible: false
            },
            dataForm: {
            },
            multipleSelection: [], // 勾选的表格的项目
            rules: {
                // fProvinceId: [{required: true, message: '请选择省份' }], // edit by cuihd at 2018/8/8
                schoolName: [{required: true, message: '请先输入学校'}], // edit by cuihd at 2018/8/8
                exueCode: [...validate.exueCode()],
                phone: [...validate.phone()]               
            },
            schoolLoading: false,
            /**
             * created by cuihd at 20180709
             * 优化批量删除教师
             * 添加相关变量
             */
            dialogTitle: '正在批量删除教师...',
            dialogTimeout: false,
            progress: 0
        }
    },
   
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表

        }),
        ...mapGetters([
            'uid'
        ])
    },
    // 初始化
    created() {
        // this.search();
    },
    watch: {// 局部刷新列表
        cacheUpdated(val) {
            val==2 && this.searchFetchData();
        }
    },

    methods: {
        // 全局获取行数
        ...mapActions(['ChangePageSize']),
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 展示添加教师弹窗
        showAddTea() {
            this.addTeaData.dialogAddTea = true;
            this.addTeaData.provinceId=this.formInline.fProvinceId
        },
        showLotImport() {
            this.addImportData.dialogLotImport = true;
            this.addImportData.provinceId=this.formInline.fProvinceId
        },
        // 点击查询 
        // search() {
        //     this.loading = true;
        //     this.searchFetchData();
        // },

        // created by cuihd at 20180711
        // 轮询接口获取未导入的数量
        batchImportProgress(obj) { // 递归轮询
            let totalNum = Number(obj.totalNum); // 强转成number类型
            batchImportForTeacherProgress(obj.timeStamp, obj.schoolId).then(res => {
                if (res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null) {
                    if (res.data.content != 0) {
                        this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                        setTimeout(() => {
                            this.batchImportProgress(obj);
                        }, 1000);
                    } else {
                        // this.btnLoading = false;
                        this.dialogTitle = '批量导入教师成功';
                        this.progress = 100;
                        setTimeout(() => {                       
                            this.dialogTimeout = false;
                            this.addSearch();
                        }, 500)
                    }
                } else {
                    this.dialogTimeout = false;
                    this.$message({
                        message: '批量导入失败！',
                        type: 'error'
                    });
                    // this.addSearch();
                }          
            }).catch(err => {
                console.log(err);
            })
        },
        // 唤出批量导入进度条（和批量删除共用一个）
        importProgress(val) {
            this.dialogTitle = '正在批量导入教师中...'; // 设置进度条的title
            this.dialogTimeout = true;
            this.progress = 0; // 初始化进度条
            this.batchImportProgress(val);
        },
        addSearch() {
            if (this.formInline.fProvinceId) {
                this.loading = true;
                this.listQuery.page=1;
                this.searchFetchData();
            } else {
                return 
            }
        },
        search(ruleForm) {
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    this.listQuery.page=1;
                    this.searchFetchData();
                } else {
                    return false;
                }
            });
        },
     
           // 获取学校id
        schoolChange(val) {
            this.formInline.schoolId = val
        },
        // 查询列表
        searchFetchData() {
            this.loading = true;
            let curPage = this.listQuery.page;
            let pageSize = this.config.pageSize;
            let provinceId = this.formInline.fProvinceId;
            let cityId = this.formInline.fCityId;
            let areaId = this.formInline.fAreaId;
            let schoolId = this.formInline.schoolId;// 学校id
            let subjectId = '';
            let name = this.formInline.name;
            let phone = this.formInline.phone;
            let exueCode = this.formInline.exueCode;// e学云ID
            getTeachersByPage(curPage, pageSize, provinceId, cityId, areaId, schoolId, subjectId, name, phone, exueCode).then(res => {
                this.loading = false;
                this.AnnounceList = res.data.content.list;
                this.listQuery.total = res.data.content.pagination.total;
            }).catch(() => {
                this.loading = false;
            });
        },
        // 跳转到 修改页面
        goToCorrect(teacherId) {
            this.$router.push({ path: `/teacherManage/correct/${teacherId}`});
        },
        teacherClass(teacherId) {
            this.$router.push({ path: `/teacherManage/teacherClass/${teacherId}`});
        },
        // 单个删除教师
        deleteListOne(teacherId) {
            this.$confirm('确定删除该教师？', '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: ' ', // warning
                title: '  '
            }).then(() => {
                this.loading = true;
                batchDeleteTeacher(teacherId).then(response => {
                    // this.$message({
                    //     type: 'success',
                    //     message: response.data.errorMsg
                    // })
                    setTimeout(() => {
                        this.searchFetchData();
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    }, 2500); // 后端教师异步删除，前端无奈做出改变，后期继续优化
                    // this.searchFetchData();
                }).catch(() => {
                    this.loading = false;
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 批量删除教师信息  传老师id数组
        deleteRoleLots() {
            let teacherIds = '';
            for (let i = 0; i < this.multipleSelection.length; i++) {
                teacherIds += this.multipleSelection[i].teacherId + ',';
            }
            teacherIds = teacherIds.substring(0, teacherIds.length - 1)
            if (teacherIds.length == 0) {
                this.$message({
                    type: 'info',
                    message: '请选择要删除的教师!'
                });
                return;
            }
            this.$confirm('将删除选中教师, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.loading = true;
                batchDeleteTeacher(teacherIds).then(res => {
                    /**
                     * created by cuihd at 20180709
                     * 优化批量删除教师
                     * 添加相关变量
                     */
                    this.loading = false;
                    let timeStamp = res.data.content.timeStamp;
                    let totalNum = res.data.content.totalNum;
                    this.dialogTitle = '正在批量删除教师...';
                    this.dialogTimeout = true;
                    this.batchProgress(timeStamp, totalNum);
                }).catch(() => {
                    this.loading = false;
                });
            }).catch(() => {
                // console.log(1);
            });
        },
        // created by cuihd at 20180709
        // 轮询接口获取未处理的数量
        batchProgress(timeStamp, totalNum) { // 递归轮询batchDeleteTeacherProgress接口
            totalNum = Number(totalNum); // 强转成number类型
            batchDeleteTeacherProgress(timeStamp).then(res => {
                if (res.data.content != '0') {
                    this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                    setTimeout(() => {
                        this.batchProgress(timeStamp, totalNum);
                    }, 1000);
                } else {
                    this.dialogTitle = '批量删除教师成功';
                    this.progress = 100;
                    setTimeout(() => {                       
                        this.dialogTimeout = false;
                        this.searchFetchData();
                    }, 1000)
                }
            }).catch(err => {
                console.log(err);
            })
        },
      
        // 初始化密码
        initPassword(teacherId, name) {
            this.$confirm('确定要初始化【'+name+'】的密码吗？', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: ' '
            }).then(() => {
                initPassword(teacherId).then(res => {
                    if (res.data.status == 200) {
                        this.$message({
                            type: 'success',
                            message: '初始化密码成功，新密码是111111'
                        });
                    } else {
                        this.$message.error(res.data.errorMsg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消初始化密码'
                });
            });
        },
        // 分页
        handleSizeChange(val) {
            this.ChangePageSize(val);
            this.$refs.formInline.validate((valid) => {
                if (valid) {
                    this.listQuery.page = 1;
                    // this.ChangePageSize(val);
                    this.searchFetchData();
                }
            })
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.listQuery.page = val;
            this.searchFetchData();
        }
    }
}
</script>
<style lang="scss">
@import '../../../styles/var';
.content {
    position: relative;
    padding: 0px;
    $bgcolor: #fff;
    // .formInline {
    //     .formBtn {
    //         width: 100%;
    //         height: 70px;
    //         border-top: 1px solid #dddddd;
    //         position: relative;
    //         .btnPosition {
    //             position: absolute;
    //             right: 0px;
    //             top: 18px;
    //         }
    //     }
    // }
}
</style>